package cn.tedu.egmvc5.base.filter;

import cn.tedu.egmvc5.pojo.vo.UserQuery;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "LogincheckFilter",urlPatterns = "/v1/user/article")
public class LogincheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //要进行类型的强转，以便使用session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        //通过session拿到当前用户
        UserQuery userQuery= (UserQuery)session.getAttribute("user");
        //判断当前用户是否存在
        if (userQuery!=null){
            filterChain.doFilter(request,response);
        }else {
            response.sendRedirect("login.html");

        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
